import { Component, Input, OnInit, OnDestroy, ElementRef, Renderer2 } from '@angular/core';
import { NavParams, ModalController } from '@ionic/angular';
import { VgAPI } from 'videogular2/core';
// import { Screenshot } from '@ionic-native/screenshot/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { RoomEchartsService } from '@services/echarts/room.echarts.service';
import { DataService } from '@services/data.service';
import { CacheService } from '@services/cache.service';
import { MyNoteService } from '@services/myNote.service';
import { DatePipe } from '@angular/common';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

export interface IMedia {
    src: string;
}

declare var window;
declare var screen;
@Component({
    selector: 'room-video',
    templateUrl: './room-video.html',
    styleUrls: ['room-video.scss']
})
export class RoomVideoModal implements OnInit, OnDestroy {

    @Input() config;
    // @ViewChild('videoView') videoListView: Scroll;

    api: VgAPI;
    options;
    showTool = true;
    projectId;
    deviceType;
    cameraPich = true;
    paramsPitch = 0;
    pitch = 0;
    currentItem: IMedia = {
        src: '',
    };

    isOnline;  // 摄像头是否在线

    constructor(private params: NavParams,
        // private viewCtrl: ViewController,
        private echart: RoomEchartsService,
        private dataservice: DataService,
        private cacheservice: CacheService,
        // private screenshot: Screenshot,
        private myNote: MyNoteService,
        private statusBar: StatusBar,
        private modalCtrl: ModalController,
        private orientation: ScreenOrientation,
        private renderer: Renderer2,
        private el: ElementRef
    ) {
        console.log('config', this.params.get('config'));
        this.config = this.params.get('config');
        this.projectId = this.cacheservice.currentProject.projectId;
        this.statusBar.hide();
    }

    ngOnInit() {
        if (window.cordova) {
            screen.orientation.lock('landscape');
        }
        this.getVideoUrl();
        // this.getChartData(this.config.message[0]);
        this.getCameraChart(this.config.videoList[this.pitch].cameraId);
        this.isOnline = this.config.videoList[0].isOnline;
        this.getImportantDeviceTypeByArea();
    }


    onPlayerReady(api: VgAPI) {
        this.api = api;
        console.log('是否存在视频资源', this.currentItem);
        this.api.getDefaultMedia().subscriptions.loadedMetadata.subscribe(res => {
            console.log('视频加载成功', res)
            this.playVideo();
        });
        // if (this.config.videoList.length > 1) {
        //     this.api.getDefaultMedia().subscriptions.ended.subscribe(this.nextVideo.bind(this));
        // }
        this.api.getDefaultMedia().subscriptions.error.subscribe(
            (error) => {
                console.log('视频加载失败')
                if (this.currentItem && this.currentItem.src) {
                    // console.log('报错啦', error);
                    this.checkUrl(this.currentItem.src);
                }
            }
        );
    }

    // nextVideo() {
    //     this.getVideoUrl();
    // }

    playVideo() {
        this.api.play();
    }

    closeModal() {
        this.modalCtrl.dismiss();
    }

    showEcharts(data) {
        this.options = this.echart.showRoomParamsChart(data);
        console.log(this.options)
    }

    refreshVideo() {
        console.log('刷新视频');
        const ele = this.el.nativeElement.querySelector('.refresh');
        this.renderer.setStyle(ele, 'animation', 'rotating 1.2s linear infinite');
        this.getVideoUrl(ele);
    }

    // 截屏
    toPhoto() {
        // const name = 'myscreenshot' + new Date().getTime() + '.jpg';
        // this.screenshot.save('jpg', 80, name).then((data) => {
        //     console.log(data);
        //     this.myNote.MyNotice('截图成功');
        // }, (err) => {
        //     console.log(err);
        //     this.myNote.MyNotice('截图失败');
        // });
    }

    choose(index) {
        console.log(this.config)
        this.isOnline = this.config.videoList[index].isOnline;
        this.pitch = index;
        this.getVideoUrl();
    }

    scrollVideo() {
        let interval;
        let count; count = 0;
        interval = setInterval(() => {
            // this.videoListView._scrollContent.nativeElement.scrollTop += 3;
            count++;
            if (count >= 20) {
                clearInterval(interval);
            }
        }, 10);
    }

    getVideoUrl(ele?) {
        this.currentItem = { src: '' };
        this.dataservice.getRoomVideoUrl(this.config.videoList[this.pitch].cameraId).subscribe(res => {
            if (ele) {
                if (res.success) {
                    setTimeout(() => {
                        console.log('刷新成功', res.data)
                        this.currentItem = { src: res.data };
                        this.renderer.removeStyle(ele, 'animation')
                    }, 2000);
                }
            } else {
                console.log('获取视频成功', res.data)
                this.currentItem = { src: res.data };
            }
        });
    }

    // 一秒钟验证一下url有没有资源
    checkUrl(url) {
        this.currentItem = { src: '' };
        setTimeout(() => {
            this.currentItem = { src: url };
        }, 1000);
    }

    getChartData(param) {
        console.log('获取曲线', param)
        if (!param) {
            return;
        }
        const displayCount = 24;
        let datacodes; datacodes = [];
        let startAndEndDate; startAndEndDate = [];
        const datepipe = new DatePipe('en-US');
        const today = datepipe.transform(new Date(), 'yyyy-MM-dd');
        const nextday = +new Date() + 1000 * 60 * 60 * 24;
        const nextdayStr = datepipe.transform(new Date(nextday), 'yyyy-MM-dd');
        startAndEndDate = [today, nextdayStr];
        for (let i = 0; i < param.deviceParameters.length; i++) {
            datacodes.push(param.deviceParameters[i].parameterCode);
        }
        this.dataservice.getDeviceParamesHistoryData(this.projectId,
            param.deviceId, datacodes, displayCount, startAndEndDate).subscribe(res => {
                console.log(res.data);
                if (res.success === true) {
                    this.showEcharts(res.data);
                }
            }, (error: any) => {
                console.log('获取折线图数据异常', error);
            });
    }

    getImportantDeviceTypeByArea() {
        this.dataservice.getImportantDeviceTypeByArea(this.config.areaId).subscribe(res => {
            if (res && res.data) {
                this.deviceType = res.data.importDevices;
            }
        });
    }

    hideOrShowTool() {
        this.showTool = !this.showTool;
    }

    selectParams(index) {
        this.cameraPich = false;
        this.paramsPitch = index;
        this.getChartData(this.config.message[index]);
        console.log(this.config)
    }

    selectCamera() {
        this.cameraPich = true;
        this.getCameraChart(this.config.videoList[this.pitch].cameraId);
    }

    getCameraChart(cameraId) {
        const datepipe = new DatePipe('en-US');
        const today = datepipe.transform(new Date(), 'yyyy-MM-dd');
        const nextday = +new Date() + 1000 * 60 * 60 * 24;
        const nextdayStr = datepipe.transform(new Date(nextday), 'yyyy-MM-dd');
        const searchTime = [today, nextdayStr];
        console.log(searchTime);
        this.dataservice.getCameraParamCurve(cameraId, 4, [1], searchTime, 24).subscribe(res => {
            if (res.success === true) {
                res.data.charts = [];
                // for (const data of res.data) {
                res.data.parameterName = "通讯状态";
                res.data.unit = "";
                res.data.max = 1;
                res.data.min = 0;
                res.data.point = [];
                for (const data of res.data.data) {
                    res.data.point.push({ x: data.triggeringTime, y: data.val });
                }
                // }
                res.data.charts[0] = res.data;
                console.log('通讯状态历史曲线', res.data.charts);
                this.showEcharts(res.data.charts);
            }
        }, (error: any) => {
            console.log('获取折线图数据异常', error);
        });
    }

    ngOnDestroy() {
        if (window.cordova) {
            screen.orientation.lock('portrait');
        }
        this.statusBar.show();
        this.statusBar.overlaysWebView(true);
    }

}
